package com.eianiao.filter;

import com.eianiao.bean.Employee;
import com.eianiao.bean.User;
import com.eianiao.utils.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author eianiao
 * @Date 2022 06
 * @Version 1.0
 **/
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //0. 转化对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //1. 获取请求地址   /backend/index.html
        String uri = request.getRequestURI();

//        System.out.println("被抓住的请求是：" + uri);


        //2. 判定是否属于直接放行的请求
        if(uri.contains("login") || uri.endsWith(".css") || uri.endsWith(".js")
                || uri.contains("images") || uri.contains("plugin") || uri.contains("style")
                || uri.endsWith(".ico") || uri.contains("sms")){
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }

        //3. 如果没有进入上面的if， 即表示要判定登录
        //3.1 从session作用域里面获取登录的时候，保存的员工对象
        Employee employee = (Employee) request.getSession().getAttribute("employee");

        //3.2 判定是否有值
        if(employee != null){ //表示已经登录了
            //在这里保存员工的id到ThreadLocal里面去
            BaseContext.setCurrentId(employee.getId());

            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }

        //3.3判断用户是否有登录
        User user = (User) request.getSession().getAttribute("user");
        System.out.println("开始检验用户*************");
        if (user != null){
            BaseContext.setCurrentId(user.getId());

            filterChain.doFilter(servletRequest,servletResponse);

            return;
        }

        //4. 如果没有进入上面的if，即表示该请求，不属于直接放行的请求，也没有登录。要跳转登录页面
        if (uri.contains("front")){
            response.sendRedirect("/front/page/login.html");

        }else {
            response.sendRedirect("/backend/page/login/login.html");

        }
    }
    }


